<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <title>阿里云OSS图片/视频上传测试</title>
  <script src="https://cdn.jsdelivr.net/npm/ali-oss/dist/aliyun-oss-sdk.min.js"></script>
</head>

<body>
  <h2>上传图片或视频到阿里云OSS</h2>
  <input type="file" id="fileInput" accept="image/*,video/*" />
  <button onclick="uploadFile()">上传</button>
  <img src="" alt="" class="my-image">
  <div id="result"></div>
  <script>
    let config = {
      region: 'oss-cn-beijing',
      bucket: 'wen-xuan',
    }
    const baseUrl = 'http://127.0.0.1:8085'
    const fileInput = document.querySelector("#fileInput");
    function uploadFile() {
      event.preventDefault();
      const file = fileInput.files[0];
      const filename = fileInput.files[0].name;
      fetch(`${baseUrl}/api/oss/get_sts_token_for_oss_upload?dateTime=${Date.now()}`, { method: "GET" })
        .then((response) => {
          return response.json();
        })
        .then(async (data) => {
          console.log(data);
          let credentials = data;

          const client = new OSS({
            // 将<YOUR_BUCKET>设置为OSS Bucket名称。
            bucket: "wen-xuan",
            // 将<YOUR_REGION>设置为OSS Bucket所在地域，例如region: 'oss-cn-hangzhou'。
            region: "oss-cn-beijing",
            authorizationV4: true,
            accessKeyId: credentials.AccessKeyId,
            accessKeySecret: credentials.AccessKeySecret,
            stsToken: credentials.SecurityToken,
          });
          const result = await client.put(file.name, file);
          console.log(result, '上传成功');
          // 上传成功后，将图片或视频的URL显示在页面上
          const imgUrl = result.url;
          const imgElement = document.querySelector(".my-image");
          imgElement.src = imgUrl;
          const resultElement = document.querySelector("#result");
          resultElement.innerHTML = "上传成功，图片或视频的URL为：" + imgUrl;
        })
        .catch((error) => {
          console.error("发生错误:", error);
        });

    }
    function realUpload() {

    }
  </script>
</body>

</html>